import 'dart:async';

import 'package:flutter/material.dart';

class SwiperUtils extends StatefulWidget {
  final double width;
  final double height;
  final List<Widget> pageList;
  const SwiperUtils(
      {super.key,
      this.width = double.infinity,
      required this.pageList,
      this.height = 200});

  @override
  State<SwiperUtils> createState() => _SwiperUtilsState();
}

class _SwiperUtilsState extends State<SwiperUtils> {
  //定义当前页数索引
  int _currIndex = 0;
  //定义控制器
  late PageController _pageController;
  //定义定时器，接受定时器返回值,便于后期销毁
  late Timer _timer;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //初始化页面控制器
    _pageController = PageController(initialPage: _currIndex);

    //定义定时器时间间隔
    const timeout = Duration(seconds: 3);
    //启动定时器并赋值
    _timer = Timer.periodic(timeout, (timer) {
      _pageController.animateToPage(
        //页面索引
        (_currIndex + 1) % (widget.pageList.length),
        //动画时间
        duration: const Duration(milliseconds: 200),
        //动画曲线
        curve: Curves.bounceIn,
      );
    });
  }

  @override
  dispose() {
    //销毁释放所有资源
    super.dispose();
    _timer.cancel();
    _pageController.dispose();
  }

  Widget pageViewBuilder() {
    //定义PageView
    Widget body = PageView.builder(
      //循环次数
      itemCount: 10000,
      //翻页次数
      itemBuilder: (context, index) {
        //使用模运算符，实现无限滚动
        return widget.pageList[index % (widget.pageList.length)];
      },
      //绑定页面控制器
      controller: _pageController,
      //页面切换监听
      onPageChanged: (index) {
        setState(() {
          //实现指示器跟随变化
          _currIndex = index % (widget.pageList.length);
        });
      },
    );
    //因为PageView默认撑满屏幕，所以设置尺寸
    body = SizedBox(width: widget.width, height: widget.height, child: body);
    return body;
  }

  //构建指示器
  Widget indicator() {
    Widget body = Row(
        mainAxisAlignment: MainAxisAlignment.center,
        //通过List.generate遍历元素，生成指定数量的指示器
        children: List.generate(widget.pageList.length, (index) {
          //定义指示器样式
          return Container(
            width: 10,
            height: 10,
            margin: const EdgeInsets.only(left: 5, right: 5),
            decoration: BoxDecoration(
                color: _currIndex == index ? Colors.white : Colors.grey,
                shape: BoxShape.circle),
          );
        }));
    //使用Positioned组件配合Stack组件，指定指示器位置
    //注意此处不能设置top属性，否则位置计算会有误
    body = Positioned(bottom: 10, left: 0, right: 0, child: body);
    return body;
  }

  @override
  Widget build(BuildContext context) {
    //绑定两个子组件到根组件中
    return Stack(
      children: [pageViewBuilder(), indicator()],
    );
  }
}
